package com.mo.redis;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.domain.Range;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * @author moon.pan
 * @program mo-all
 * @apiNote
 * @since 2022/6/20
 */
@Component
@Slf4j
@ConditionalOnProperty(value = "spring.redis.host")
public class RedisStreamHandler {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final ExecutorService executorService = ThreadUtil.newSingleExecutor();

    @PostConstruct
    public void init() {
        executorService.submit(() -> {
            while (true) {
                try {
                    ThreadUtil.sleep(1000);
                    PendingMessagesSummary pending = redisTemplate.opsForStream().pending("async_queue", "group1");
                    if (pending != null) {
                        long totalPendingMessages = pending.getTotalPendingMessages();
                        PendingMessages pendingMessages = redisTemplate.opsForStream().pending("async_queue", "group1", pending.getIdRange(), totalPendingMessages);
                        for (PendingMessage pendingMessage : pendingMessages) {
                            Duration lastDelivery = pendingMessage.getElapsedTimeSinceLastDelivery();
                            if (lastDelivery.getSeconds() >= 45) {
                                // 消息超时, 重新消费
//                                long totalDeliveryCount = pendingMessage.getTotalDeliveryCount();
                                System.out.println("消息超时, 重新消费 : " + pendingMessage.getIdAsString());

                                // 手动消费 :: 确认旧消息, 重新入队
                                List<MapRecord<String, Object, Object>> asyncQueue = redisTemplate.boundStreamOps("async_queue").range(Range.rightOpen(pendingMessage.getIdAsString(), pendingMessage.getIdAsString()));

                                if (asyncQueue != null) {
                                    for (MapRecord<String, Object, Object> record : asyncQueue) {

                                        MapRecord<String, Object, Object> message = StreamRecords.mapBacked(record.getValue()).withStreamKey("async_queue");
                                        redisTemplate.opsForStream().add(message);

                                        redisTemplate.opsForStream().acknowledge("group1", record);
                                        redisTemplate.opsForStream().delete(record);
                                    }
                                }
                            }
                        }
                    }

                } catch (Exception e) {

                }
            }
        });
    }
}
